<template>
  <el-row :gutter="0">
  <el-col :xs="2" :sm="3" :md="4" :lg="4" :xl="4">
    <div class="hidBoth">郭于</div>
  </el-col>
  <el-col :xs="20" :sm="18" :md="16" :lg="16" :xl="16">
  <div>
    <h1>商品列表</h1>
    <!-- 功能 start -->
    <el-row >
        <div class="buttonTop">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            round
          >
            添加新商品
          </el-button>
          </div>
    </el-row>
    <!-- 功能 end -->
    <!-- 主要部分 -->
    <el-row :gutter="10">
      <el-table :data="listData" style="width: 100%" 
      border :default-sort = "{prop: 'ctime,number', order: 'descending'}"
      fixed
      >
        <el-table-column prop="name" label="商品名称" min-width='25%' align="center"> </el-table-column>
        <el-table-column sortable prop="ctime" label="创建时间" min-width='30%'  align="center">
          <template slot-scope="scope">
            {{ scope.row.ctime | dataFormat }}
          </template>
        </el-table-column>
        <el-table-column  sortable prop="number" label="数量" min-width='9%'  align="center">
        </el-table-column>
        <el-table-column label="单价/总价" min-width='25%'  align="center">
          <template slot-scope="scope">
            
        <el-row :gutter="0">            
            <el-col :xs="23" :sm="23" :md="11" :lg="11" :xl="11"> 
              {{scope.row.price}} 元
            </el-col>
            <el-col :xs="1" :sm="1" :md="2" :lg="2" :xl="2" align="left"> 
              /
            </el-col>
            <el-col :xs="24" :sm="24" :md="11" :lg="11" :xl="11">
              {{scope.row.price*scope.row.number}} 元
            </el-col>
        </el-row>

        </template>
        </el-table-column>
        <el-table-column label="操作" min-width='11%'  align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click.prevent="remove(scope.$index)"
            >
            </el-button>
        </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 提示框 -->
    <el-dialog
      title="添加商品"
      :visible.sync="addDialogVisible"
      width="70%"
      @close="addDialogClose"
    >
      <!-- Start 添加表单 -->
      <!-- model 是当前表单要绑定的数据对象 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="5rem" 
      >
        <!-- 在el-form-item 中，label 用来指定label标签的内容 -->
        <!-- 在el-form-item prop 用来指定当前项目使用哪个验证规则 规则从 addFormRules 上取得-->
        <el-form-item label="品牌名称" prop="productName">
          <el-input v-model="addForm.productName"></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="productNum">
          <el-input-number v-model="addForm.productNum" :min="1"></el-input-number>
        </el-form-item>       

        <el-form-item label="单价" prop="productPrc">
          <el-input-number v-model="addForm.productPrc" :min="1"></el-input-number>
          总价: {{addForm.productNum}}  * {{addForm.productPrc}} = {{addForm.productNum*addForm.productPrc}} 元
        </el-form-item>   
        <el-form-item label="商品细节" prop="productDtl">
          <el-input   type="textarea" :rows="5" placeholder="请输入内容（可忽略）" v-model="addForm.productDtl"></el-input>
        </el-form-item>

      <el-form-item label="商品图片" prop="productImg">
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="getImgNme"
          :on-exceed="handleExceed"
          :limit="1"
          ref="imgRef"
          >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="addDialogClose">重置</el-button>
        <el-button type="primary" @click="addNewProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
    </el-col>
  <el-col :xs="2" :sm="3" :md="4" :lg="4" :xl="4">
    <div class="hidBoth">郭于</div>
  </el-col>
  </el-row > 
</template>

<script>

export default {
  data() {
    return {
      listData:[],
      // 控制添加新品牌的对话框的显示与隐藏
      addDialogVisible: false,
      // 添加表单所绑定的数据对象
      addForm: {
        productName: "",
        productNum: "",
        productPrc: "",
        productDtl:'',
        productImg:'',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        // 验证：品牌名称是否合法的 规则
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],        
        productNum: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],

      },
        dialogImageUrl : '',
        dialogVisible : false,
    };
  },
  created() {
    this.getProductList();
    
  },
  methods: {
    // 从 localStorage 获取数据
    getProductList() {
      this.listData = JSON.parse(localStorage.getItem("productList"));

      if (this.listData !== null) {
        return this.listData;
      } else {
        return [];
      }
    },
    // 对话框关闭时对表单重置的处理函数
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
      this.$refs.imgRef.clearFiles();
    },

    // 点击按钮，添加新品牌
    addNewProduct() {
      const local = this.getProductList();
      const newData = {
        id:local.length+1,
        name: this.addForm.productName,  
        ctime: new Date(),
        number:this.addForm.productNum,
        price:this.addForm.productPrc,
        detail:this.addForm.productDtl,
        imgData:this.addForm.productImg,
      };

      if(newData.name == '')
      return this.$message.error("添加商品失败！");

      if(newData.number < 1)
      return this.$message.error("添加商品失败！");
      
      if(newData.imgData ==='')
      {
        newData.imgData='../images/错误.jpg'
      }

      if(newData.price ==='')
      {
        newData.price=1
      }

      local.push(newData);

      localStorage.setItem("productList", JSON.stringify(local));

      this.$message.success("添加商品成功！");
      // 隐藏对话框
      this.addDialogVisible = false;
    },
    getImgNme(file) {
    const isJPG = file.raw.type === 'image/jpeg';
    const isPNG = file.raw.type === 'image/png';
    const isLt200k = file.size / 1024  < 200;
    if ((!isJPG)&&(!isPNG)) {
      this.$message.error('上传图片只能是 JPG或PNG 格式!');
      file.url=''
      return
    }    
    if (!isLt200k) {
      this.$message.error('上传图片大小不能超过 2MB!');
      file.url=''
      return
    }
    this.addForm.productImg='../images/'+file.name;
    return isJPG && isPNG && isLt200k;    
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 根据id单独删除数据
    async remove(id) {
      let removeData = localStorage.getItem("productList");

      removeData = JSON.parse(removeData);

      await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeData.splice(id, 1);
          localStorage.setItem("productList", JSON.stringify(removeData));
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      this.getProductList();
    },
    
 
  },
};
</script>

<style lang="less" scope>
h1 {
    padding: 0.8rem;
    border-left: 0.3rem solid #ffd04b;
    border-radius: 0 0.1rem 0.1rem 0;
    background-color: #f2f2f2;
    margin-block-start: 1rem;
    margin-block-end: 1rem;
    margin-inline-start: 0rem;
    margin-inline-end: 0rem;
}
.buttonTop {
  float: right;
  margin-bottom: 1rem;
  margin-right: 3rem;
}

// 表格样式
// element UI 自带的选择器
.cell {
  font-size: 1.3rem;
}

// 表单样式
.formNum {
  // 上传图片
img {
  width: 20px;
}
}
</style>